package com.solution.admin.sysconfig.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.solution.admin.sysconfig.entity.WechatArticleEntity;
import com.solution.admin.sysconfig.entity.WechatMsgConfigEntity;
import com.solution.admin.sysconfig.service.WechatArticleService;
import com.solution.admin.sysconfig.service.WechatMsgConfigService;
import com.solution.common.config.PublicConfig;
import com.solution.common.constants.PublicStatus;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.wx.core.constants.WechatConstants.MsgTypeValueEnum;
import com.solution.wx.core.entity.sendmsg.ArticleEntity;
import com.solution.wx.core.entity.sendmsg.ArticlesEntity;
import com.solution.wx.core.util.WechatUtil;

/**
 * 微信消息管理web控制层
 * @author solin
 * @date 2017-11-27 19:04:20
 */
@RequestMapping("/wechatMsgConfig")
@Controller("wechatMsgConfigController")
public class WechatMsgConfigController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(WechatMsgConfigController.class);

	@Autowired
	private WechatMsgConfigService wechatMsgConfigService;
	@Autowired
	private WechatArticleService wechatArticleService;
	
	/**
	 * 跳转微信消息管理查询页面 10828217@qq.com
	 * @param WechatMsgConfig 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author solin
 	 * @date 2017-11-27 19:04:20
	 */
	@RequestMapping("/toListWechatMsgConfigPage")
	public String toListWechatMsgConfigPage(WechatMsgConfigEntity wechatMsgConfig, HttpServletRequest request) {
		return "sysconfig/wechatMsgConfig_list";
	}
	
	/**
	 * 跳转到选择消息页面
	 * @param wechatMsgConfig
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月30日 下午4:18:44
	 */
	@RequestMapping("/toSelectWechatMsgConfigPage")
	public String toSelectWechatMsgConfigPage(WechatMsgConfigEntity wechatMsgConfig, HttpServletRequest request) {
		return "sysconfig/wechatMsgConfig_select";
	}
	
	/**
	 * 跳转到文章预览页
	 * @param msgId
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年12月8日 上午10:33:26
	 */
	@RequestMapping("/toArticleViewPage")
	public String toArticleViewPage(long msgId, int index, HttpServletRequest request) {
		WechatMsgConfigEntity wechatMsgConfigInfo = wechatMsgConfigService.getWechatMsgConfigById(msgId);
		
		if (MsgTypeValueEnum.ARTICLE.equals(wechatMsgConfigInfo.getMsgType())) {
			request.setAttribute("date", DateUtils.formatDate(wechatMsgConfigInfo.getCreateTime(), "yyyy-MM-dd"));
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("msgId", msgId);
			List<WechatArticleEntity> articleList = wechatArticleService.listWechatArticle(param);
			if (null != articleList && articleList.size() > 0) {
				request.setAttribute("article", articleList.get(index));
			} else {
				request.setAttribute("article", new WechatArticleEntity());
			}
		}
		
		return "sysconfig/wechatMsgConfig_view";
	}

	/**
	 * 分页查询微信消息管理列表
	 * @param wechatMsgConfig 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author solin
 	 * @date 2017-11-27 19:04:20
	 */
	@RequestMapping("/listWechatMsgConfigPage")
	@ResponseBody
	public JSONGrid listWechatMsgConfigPage(WechatMsgConfigEntity wechatMsgConfig, HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap.put("msgType", wechatMsgConfig.getMsgType());
			paramMap.put("msgTitle", wechatMsgConfig.getMsgTitle());
			paramMap.put("status", wechatMsgConfig.getStatus());
			PageBean pageBean = wechatMsgConfigService.listWechatMsgConfigPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(),pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询微信消息管理失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	/**
	 * 跳转新增页面
	 * @return string 跳转页面路径
	 * @author solin
 	 * @date 2017-11-27 19:04:20
	 */
	@RequestMapping("/toAddWechatMsgConfig")
	public String toAddWechatMsgConfig(HttpServletRequest request) {
		request.setAttribute("opFlag", "add");
		return "sysconfig/wechatMsgConfig_form";
	}

	/**
	 * 跳转编辑页面
	 * @return string 跳转页面路径
	 * @author solin
 	 * @date 2017-11-27 19:04:20
	 */
	@RequestMapping("/toUpdateWechatMsgConfig")
	public String toUpdateWechatMsgConfig(HttpServletRequest request) {
		// 编辑操作
		request.setAttribute("opFlag", "edit");
		long id = Long.valueOf(request.getParameter("id"));
		try {
			//获取消息
			WechatMsgConfigEntity wechatMsgConfig = wechatMsgConfigService.getWechatMsgConfigById(id);
			//如果是图文，则获取文章列表
			if (MsgTypeValueEnum.ARTICLE.equals(wechatMsgConfig.getMsgType())) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("msgId", id);
				List<WechatArticleEntity> articleList = wechatArticleService.listWechatArticle(param);
				wechatMsgConfig.setArticleList(articleList);
			}
			request.setAttribute("wechatMsgConfig", wechatMsgConfig);
		} catch (Exception e) {
			handleException("跳转编辑微信消息管理页面错误", logger, e);
		}
		return "sysconfig/wechatMsgConfig_form";
	}


	/**
	 * 新增或保存微信消息管理
	 * @param request 请求对象
	 * @param wechatMsgConfigEntity 微信消息管理实体
	 * @return
	 * @author solin
 	 * @date 2017-11-27 19:04:20
	 */
	@RequestMapping("/saveOrUpdateWechatMsgConfig")
	@ResponseBody
	public Map<String, Object> saveWechatMsgConfig(HttpServletRequest request, WechatMsgConfigEntity wechatMsgConfigEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			
			//获取图片上传到微信服务器返回的媒体ID
			if (StringUtil.isNotEmpty(wechatMsgConfigEntity.getImageUrl())) {
				//获取封面图片阿里云地址
				String ossImageUrl = wechatMsgConfigEntity.getImageUrl();
				//将阿里云图片下载到本地
				String fileName = ossImageUrl.substring(ossImageUrl.lastIndexOf("/")+1); 
				String fullFileName = request.getSession().getServletContext().getRealPath("/").concat("download\\").concat(fileName); //保存到服务器的图片文件路径
				String url = PublicConfig.IMG_ROOT_URL.concat(ossImageUrl);
				File file = WechatUtil.httpRequestToFile(fullFileName, url, "GET", null);
				
				//将封面图片上传微信服务器，获取返回的mediaId
				JSONObject coverResObj = WechatUtil.uploadMedia(file, WechatUtil.getAccessToken(), "image");
				if (coverResObj.containsKey("errcode")) {
					if (coverResObj.getInteger("errcode") != 0) {
						logger.error("上传图文消息素材失败 errcode:{}, errmsg:{} ", coverResObj.getInteger("errcode"), coverResObj.getString("errmsg"));  
					}
				}
				String media_id = coverResObj.getString("media_id");
				wechatMsgConfigEntity.setImageMediaId(media_id);
			}
			
			//获取图文上传到微信服务器返回的媒体ID 
			if (StringUtil.isNotEmpty(request.getParameter("articles"))) {
				List<WechatArticleEntity> wechatArticleList = JSONArray.parseArray(request.getParameter("articles"), WechatArticleEntity.class);
				wechatMsgConfigEntity.setArticleList(wechatArticleList);
				//判断文章列表中是否含有类型链接类型为外部链接地址的文章
				boolean isExternal = false;
				for (WechatArticleEntity wechatArticle : wechatArticleList)  {
					if (2 == wechatArticle.getLinkType()) {
						isExternal = true;
						break;
					}
				}
				
				if (!isExternal) {
					//上传图文消息素材
					String fileDirPath = request.getSession().getServletContext().getRealPath("/").concat("download\\");
					List<ArticleEntity> articleList = new ArrayList<ArticleEntity>();
					for (WechatArticleEntity wechatArticle : wechatArticleList) {
						//将封面图片上传到微信服务器并获取返回的额媒体ID 
						String ossImageUrl = wechatArticle.getThumbImageUrl();
						//将阿里云图片下载到本地
						String fileName = ossImageUrl.substring(ossImageUrl.lastIndexOf("/")+1); 
						String fullFileName = fileDirPath.concat(fileName); //保存到服务器的图片文件路径
						String url = PublicConfig.IMG_ROOT_URL.concat(ossImageUrl);
						File file = WechatUtil.httpRequestToFile(fullFileName, url, "GET", null);
						
						//将封面图片上传微信服务器，获取返回的mediaId
						JSONObject coverResObj = WechatUtil.uploadMedia(file, WechatUtil.getAccessToken(), "image");
						if (coverResObj.containsKey("errcode")) {
							if (coverResObj.getInteger("errcode") != 0) {
								logger.error("上传图文消息素材失败 errcode:{}, errmsg:{} ", coverResObj.getInteger("errcode"), coverResObj.getString("errmsg"));  
							}
						}
						String thumb_media_id = coverResObj.getString("media_id");
						
						ArticleEntity article = new ArticleEntity();
						article.setThumb_media_id(thumb_media_id);
						article.setAuthor(wechatArticle.getAuthor());
						article.setTitle(wechatArticle.getTitle());
						//article.setContent_source_url(msgEntity.getLinkUrl());
						article.setContent(WechatUtil.replaceImgUrlOfMpNews(wechatArticle.getContent(), 0, fileDirPath));
						article.setDigest(wechatArticle.getDigest());
						article.setShow_cover_pic(0);
						articleList.add(article);
					}
					ArticlesEntity acticles = new ArticlesEntity();
					acticles.setArticles(articleList);

					JSONObject acticleResObj = WechatUtil.uploadNews(acticles, WechatUtil.getAccessToken());
					if (acticleResObj.containsKey("errcode")) {
						if (acticleResObj.getInteger("errcode") != 0) {
							logger.error("上传图文消息素材失败 errcode:{}, errmsg:{} ", acticleResObj.getInteger("errcode"), acticleResObj.getString("errmsg"));  
						}
					}
					String article_media_id = acticleResObj.getString("media_id");
					wechatMsgConfigEntity.setArticleMediaId(article_media_id);
				} else {
					wechatMsgConfigEntity.setArticleMediaId("");
				}
				
			}
			
			String id = request.getParameter("id");
			if(StringUtil.isNotEmpty(id)){
				result = wechatMsgConfigService.updateWechatMsgConfig(wechatMsgConfigEntity);
			}else{
				
				wechatMsgConfigEntity.setStatus(STATUS.ENABLED.getId());
				wechatMsgConfigEntity.setCreater(this.getUserCode());
				
				//获取上传到微信服务器的图文消息媒体ID
				
				result = (int)wechatMsgConfigService.saveWechatMsgConfig(wechatMsgConfigEntity);
			}
			resultMap.put(PublicStatus.RESULT_CODE, result > 0 ? 1 : 0);
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, 0);
			handleException("添加微信消息管理失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 设置状态
	 * @param request
	 * @param id
	 * @param status
	 * @return
	 * @author: solin
	 * @date: 2017年11月29日 下午4:32:07
	 */
	@RequestMapping("/toSetWechatMsgConfigStatus")
	@ResponseBody
	public Map<String, Object> toSetWechatMsgConfigStatus(HttpServletRequest request, Long id, int status) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			WechatMsgConfigEntity wechatMsgConfigEntity = new WechatMsgConfigEntity();
			wechatMsgConfigEntity.setId(id);
			wechatMsgConfigEntity.setStatus(status);
			result = wechatMsgConfigService.updateStatus(wechatMsgConfigEntity);
			resultMap.put(PublicStatus.RESULT_MSG, "设置成功!");
			resultMap.put(PublicStatus.RESULT_CODE, result > 0 ? 1 : 0);
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, 0);
			handleException("添加微信消息管理失败", logger, e);
		}
		
		return resultMap;
	}
	
	/**
	 * 删除
	 * @param request
	 * @param id
	 * @return
	 * @author: solin
	 * @date: 2017年11月29日 下午4:38:12
	 */
	@RequestMapping("/removeWechatMsgConfig")
	@ResponseBody
	public Map<String, Object> removeWechatMsgConfig(HttpServletRequest request, long id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			result = wechatMsgConfigService.deleteWechatMsgConfigById(id);
			resultMap.put(PublicStatus.RESULT_MSG, "删除成功!");
			resultMap.put(PublicStatus.RESULT_CODE, result > 0 ? 1 : 0);
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, 0);
			handleException("添加微信消息管理失败", logger, e);
		}
		return resultMap;
	}
}
